package util

import (
	"hash/crc32"
	"reflect"
	"strconv"
	"strings"
	"unsafe"
)

// String converts slice to string without copy.
// Use at your own risk.
func String(b []byte) (s string) {
	if len(b) == 0 {
		return ""
	}
	pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
	pstring.Data = pbytes.Data
	pstring.Len = pbytes.Len
	return
}

// Slice converts string to slice without copy.
// Use at your own risk.
func Slice(s string) (b []byte) {
	pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
	pbytes.Data = pstring.Data
	pbytes.Len = pstring.Len
	pbytes.Cap = pstring.Len
	return
}

func BytesToString(b []byte) (s string)  {
	if len(b) == 0 {
		return ""
	}
	s = "["
	for _,j := range b{
		s = s + strconv.FormatInt(int64(j),10) + ","
	}
	s = s + "]\n"
	return
}

func ReplacePay(origin string)(target string)  {
	target = origin
	for i:=11;i>-1;i--{
		item := strconv.Itoa(i)
		target = strings.Replace(target,"pay_bill_"+item,"pay_bill",-1)
		target = strings.Replace(target,"pay_purchase_"+item,"pay_purchase",-1)
		target = strings.Replace(target,"wallet_other_"+item,"wallet_other",-1)
		target = strings.Replace(target,"history_pay_bill_"+item,"history_pay_bill",-1)
		target = strings.Replace(target,"history_pay_purchase_"+item,"history_pay_purchase",-1)
		target = strings.Replace(target,"history_wallet_other_"+item,"history_wallet_other",-1)
	}
	//target = strings.Replace(target,"`pay`.","`test`.",-1)
	return
}


func StringHashcode(s string) int {
	v := int(crc32.ChecksumIEEE([]byte(s)))
	if v >= 0 {
		return v
	}
	if -v >= 0 {
		return -v
	}
	// v == MinInt
	return 0
}
